/**
 *
 * User: rendong
 * Date: 12-9-4
 * Time: 下午10:38
 * $Id: GStage.js 12 2012-09-10 16:47:05Z rendong237@gmail.com $
 */

/**
 * 初始化 一个canvas对应一个stage
 * @param canvas
 * @param bgcolor
 * @param frameRate
 * @constructor
 */
function GStage(canvas, bgcolor, frameRate){
    this.canvas = canvas;
    this.context = canvas.getContext("2d");

    this.stageHeight = this.canvas.height;
    this.stageWidth = this.canvas.width;
    this.stage = this;

    this.frameRate = frameRate;
    this._frameTime = 1000 / frameRate;
    this.bgColor = bgcolor;

    this.context.fillStyle = this.bgColor;
    this.context.fillRect(0,0, this.stageWidth, this.stageHeight);

    // 开始渲染

    var past = new Date().getTime();
    var self = this;
    function doRender()
    {
        var now = new Date().getTime();
        if (now - past >= self._frameTime){
            self.StageRender();

            past = now;
        }

        requestAnimationFrame(doRender);
    }

    doRender();
}

GStage.extend(new GDisplayObjectContainer());

/**
 * 背景颜色
 * @type {Number}
 */
GStage.prototype.bgColor = "";

/**
 * 帧率
 * @type {Number}
 */
GStage.prototype.frameRate = 24;
GStage.prototype._frameTime = 1000 / 24;
GStage.prototype._pastRenderTime = 0;
/**
 * 是否显示帧率
 * @type {Boolean}
 */
GStage.prototype.showFrameRate = true;

/**
 * 舞台宽度
 * @type {Number}
 */
GStage.prototype.stageWidth  = 0;

/**
 * 舞台高度
 * @type {Number}
 */
GStage.prototype.stageHeight  = 0;

/**
 * 画布
 * @type {HTMLCanvasElement}
 */
GStage.prototype.canvas = null;
/**
 * 2d上下文
 * @type {CanvasRenderingContext2D}
 */
GStage.prototype.context = null;

/**
 * 主渲染函数
 */
GStage.prototype.StageRender = function()
{
    var now = new Date().getTime();
    var currentFrame = Math.ceil(1000 / (now - this._pastRenderTime));
    this._pastRenderTime = now;

    // 触发事件
    this.dispatchEventByType(GEvent.ENTER_FRAME);

    var i= 0, len=0;
    var disp;
    var dirtyRect;

    // 计算重绘区域
    var dirtyRect = new GRect(0,0,0,0);

    GCalcDirtyRect(dirtyRect, this, new GRect(0,0,this.stageWidth,this.stageHeight), this.stageWidth, this.stageHeight);

    console.log(dirtyRect);
    // 进行绘制
    this.context.clearRect(0,0, this.stageWidth, this.stageHeight);
    for(i=0,len=this.numChild(); i < len; i++){
        disp = this._childs[i];
        disp.render(dirtyRect);
        disp.isReDraw = false;

        // TODO:子对象渲染
    }

    // 显示帧率
    if (this.showFrameRate){
        this.context.font = "25px serif"
        this.context.fillStyle = "#FF0000";
        this.context.fillText ("FPS:" + currentFrame,0, 25);
    }
}